﻿#include "remind.h"
#include "ui_remind.h"

Remind::Remind(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Remind)
{
    ui->setupUi(this);

    table=TD_TRIGGER;

    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);

    updateView();
    createMenu();
}

Remind::~Remind()
{
    delete ui;
}

void Remind::updateView()
{
    model->setTable(table);
    model->setFilter(QString("topic='%1'").arg(T_REMIND));
    model->select();

    ui->tableView->hideColumn(0);   //id
    ui->tableView->hideColumn(1);   //topic

    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("关键字"));    //label
    ui->tableView->setColumnWidth(2,NAME_WIDTH);

    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("提示内容"));  //detail
    ui->tableView->hideColumn(4);   //addition
}

void Remind::generateMenu()
{
    menu->addAction(QStringLiteral("添加提醒... (F1)"),this,&Remind::newItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新视图 (F5)"),this,&Remind::updateView);
    menu->addSeparator();
    menu->addAction(QStringLiteral("删除 (Delete)"),this,&Remind::removeItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("撤销 (Ctrl+Z)"),this,&Remind::revert);
    menu->addAction(QStringLiteral("保存 (Ctrl+S)"),this,&Remind::save);
}

void Remind::newItem()
{
    AddRemind item(this);
    if(item.exec() == QDialog::Accepted)
        updateView();
}

void Remind::removeItem()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(index.isValid())
        model->removeRow(index.row());
}

void Remind::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S)
        save();
    else if(event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_Z)
        revert();
    else
    {
        switch (event->key()) {
        case Qt::Key_F1:
            newItem();
            break;
        case Qt::Key_F5:
            updateView();
            break;
        case Qt::Key_Delete:
            removeItem();
            break;
        }
    }
}
